const cookieparser = process.server ? require('cookieparser') : undefined
const Cookie = require('js-cookie')

export const state = () => ({
  user: null,
})

export const mutations = {
  setUser(state, data) {
    state.user = data
  },
}

export const actions = {
  nuxtServerInit({ commit }, { req }) {
    let user = null
    if (req && req.headers && req.headers.cookie) {
      const parsed = cookieparser.parse(req.headers.cookie)
      try {
        user = JSON.parse(parsed.user)
      } catch (err) {
        // No valid cookie found
      }
    }
    commit('setUser', user)
  },
  login({ commit }, data) {
    commit('setUser', data)
    Cookie.set('user', data)
  },
  logout({ commit }) {
    commit('setUser', null)
    Cookie.remove('user')
  },
}
